//
//  TextFollowViewController.m
//  Learn
//
//  Created by  on 2024/4/12.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "TextFollowViewController.h"
#import "TestFinishViewController.h"
#import "HomeRequest.h"
#import "WordReadResultView.h"
#import "TextItemTableViewCell.h"
#import "PlayManager.h"
#import "SubmitWorkViewController.h"
#import "RecordHelper.h"
#import "PcmPlayer.h"

@interface TextFollowViewController ()<UITableViewDelegate, UITableViewDataSource,IFlyDetectionDelegate,PlayManagerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) WordReadResultView *scoreView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSString *baseUrl;
@property (nonatomic, strong) UILabel *stepL;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic,strong) IFlyDetection *detection;//评测对象
@property (nonatomic,strong) RecordHelper *recordHelper;
@property (nonatomic , assign)BOOL isRecording;
@property (nonatomic , assign)BOOL isAutomatic; // 是否自动

@property (nonatomic, assign) NSUInteger currentIndex;

@property (nonatomic, strong) UIButton *autoBtn;
@property (nonatomic, strong) UIButton *handBtn;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) PcmPlayer *pcmPlay;
@end

@implementation TextFollowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isAutomatic = YES;
    self.title = self.unitWordModel.resourceName;
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.recordHelper = [[RecordHelper alloc] init];
    [PlayManager sharPlayManager].delegate = self;
    self.detection.delegate = self;
    [self.detection evalutType:0];
    [self.detection evalutLanguage:1];
    [self setUI];
    [self loadData];
    
}

- (void)loadData {
    [HomeRequest getTextBookWordInfoWithId:self.unitWordModel.versionId moduleId:self.unitWordModel.moduleId Result:^(TextBookUnitSourceListModel *list) {
        self.baseUrl = list.resmain;
        self.dataArr = list.textResource;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.stepL.text = [NSString stringWithFormat:@"1/%lu",(unsigned long)self.dataArr.count];
            self.progressView.progress = 0.0;
        });
        DebugLog(@"%@",list);
        [self.tableView reloadData];
    }];
}

- (void)setUI {
    UILabel *stepL = [[UILabel alloc] init];
    stepL.text = @"";
    stepL.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    stepL.textColor = rgba(142, 142, 142, 1);
    stepL.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:stepL];
    self.stepL = stepL;
    [stepL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10);
        make.top.equalTo(self.view.mas_top).offset(10 + NavigationBarHeight);
    }];
    
    UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    [progressView setProgress:0.6];
    [self.view addSubview:progressView];
    self.progressView = progressView;
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(stepL.mas_right).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-93);
        make.centerY.equalTo(stepL.mas_centerY);
        make.height.offset(2);
    }];
    
    UIView *typeView = [[UIView alloc] init];
    typeView.backgroundColor = rgba(12, 183, 108, 1);
    typeView.layer.cornerRadius = 11;
    typeView.layer.masksToBounds = YES;
    [self.view addSubview:typeView];
    [typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(stepL.mas_centerY);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.width.offset(73);
        make.height.offset(22);
    }];
    
    UIButton *autoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    autoBtn.backgroundColor = UIColor.whiteColor;
    [autoBtn setTitle:@"自动" forState:UIControlStateNormal];
    [autoBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
    autoBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    autoBtn.layer.cornerRadius = 10;
    autoBtn.layer.masksToBounds = YES;
    [autoBtn bk_whenTapped:^{
        self.isAutomatic = YES;
        self.autoBtn.backgroundColor = UIColor.whiteColor;
        [self.autoBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
        self.handBtn.backgroundColor = rgba(12, 183, 108, 1);
        [self.handBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }];
    [typeView addSubview:autoBtn];
    self.autoBtn = autoBtn;
    [autoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(typeView.mas_left);
        make.centerY.equalTo(typeView.mas_centerY);
        make.height.offset(20);
        make.width.offset(36);
    }];
    
    UIButton *handBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    handBtn.backgroundColor = rgba(12, 183, 108, 1);
    [handBtn setTitle:@"手动" forState:UIControlStateNormal];
    [handBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    handBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    handBtn.layer.cornerRadius = 10;
    handBtn.layer.masksToBounds = YES;
    [handBtn bk_whenTapped:^{
        self.isAutomatic = NO;
        self.handBtn.backgroundColor = UIColor.whiteColor;
        [self.handBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
        self.autoBtn.backgroundColor = rgba(12, 183, 108, 1);
        [self.autoBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    }];
    [typeView addSubview:handBtn];
    self.handBtn = handBtn;
    [handBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(typeView.mas_right);
        make.centerY.equalTo(typeView.mas_centerY);
        make.height.offset(20);
        make.width.offset(36);
    }];
    
    self.tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,NavigationBarHeight + 50, SCREEN_W, SCREEN_H - NavigationBarHeight - SafeAreaBottomHeight - 160) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    if (@available(iOS 13.0, *)) {
        [self.tableView setAutomaticallyAdjustsScrollIndicatorInsets:NO];
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.tableView.backgroundColor=[UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 60;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"TextItemTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TextItemTableViewCell"];

    self.scoreView = [[WordReadResultView alloc] init];
    [self.view addSubview:self.scoreView];
    [self.scoreView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20);
        make.size.mas_equalTo(CGSizeMake(100, 120));
        make.bottom.equalTo(self.view).offset(-120);
    }];
    self.scoreView.hidden = YES;
    
    UIButton *centerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [centerBtn setImage:[UIImage imageNamed:@"luyin"] forState:UIControlStateNormal];
    [centerBtn bk_whenTapped:^{
        self.scoreView.hidden = YES;
        TextBookUnitTextModel *model = self.dataArr[self.currentIndex];
        [self recordTextWithText: model.name];
    }];
//    [centerBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:centerBtn];
    [centerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-48 - SafeAreaBottomHeight);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.height.offset(52);
    }];
    
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [finishBtn setTitle:@"完成录音" forState:UIControlStateNormal];
    [finishBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
    finishBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    [finishBtn bk_whenTapped:^{
//        if (self.timer == nil) {
//            self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0
//                                                              target:self
//                                                            selector:@selector(timerFired:)
//                                                            userInfo:nil
//                                                             repeats:YES];
//        }
    }];
    [self.view addSubview:finishBtn];
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-45);
        make.centerY.equalTo(centerBtn.mas_centerY);
        make.height.offset(40);
    }];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H - SafeAreaBottomHeight - 28, SCREEN_W, 28)];
    bottomView.backgroundColor = rgba(12, 183, 108, 0.1);
    [self.view addSubview:bottomView];
    
    UIButton *playStatusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playStatusBtn setImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
    [playStatusBtn bk_whenTapped:^{
        [self.detection cancle];
        [[PlayManager sharPlayManager] pause];
    }];
    [bottomView addSubview:playStatusBtn];
    [playStatusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_left);
        make.centerY.equalTo(bottomView.mas_centerY);
        make.height.offset(28);
        make.width.offset(58);
    }];
    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextBtn setTitle:@"播放全文" forState:UIControlStateNormal];
    nextBtn.layer.cornerRadius = 11;
    nextBtn.layer.borderColor = rgba(12, 183, 108, 1).CGColor;
    nextBtn.layer.borderWidth = 1;
    nextBtn.layer.masksToBounds = YES;
    [nextBtn setTitleColor:rgba(12, 183, 108, 1) forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    [nextBtn bk_whenTapped:^{
        if (self.timer == nil) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                                              target:self
                                                            selector:@selector(timerFired:)
                                                            userInfo:nil
                                                             repeats:YES];
        }
    }];
    [bottomView addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_right).offset(-20);
        make.centerY.equalTo(bottomView.mas_centerY);
        make.height.offset(22);
        make.width.offset(80);
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TextItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TextItemTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"TextItemTableViewCell" owner:self options:nil] lastObject];
    }
    TextBookUnitTextModel *model = self.dataArr[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self changeModel];
    
    TextBookUnitTextModel *model = self.dataArr[indexPath.row];
    self.currentIndex = indexPath.row;
    self.stepL.text = [NSString stringWithFormat:@"%lu/%lu", (unsigned long)(self.currentIndex + 1),(unsigned long)self.dataArr.count];
    self.progressView.progress = (float)self.currentIndex/(self.dataArr.count - 1);
    model.isRead = !model.isRead;
    [self lesson];
    [self.tableView reloadData];
    
    if (self.currentIndex == self.dataArr.count - 1) {
        SubmitWorkViewController *vc = [[SubmitWorkViewController alloc] init];
        vc.unitWordModel = self.unitWordModel;
        vc.dataArr = self.dataArr;
        vc.type = @"课文";
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)timerFired:(NSTimer *)timer {
    // 计时器触发时执行的方法
    TextBookUnitTextModel *model = self.dataArr[self.currentIndex];
    model.isRead = !model.isRead;
    [self lesson];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0]; // 滚动到第一个 section 的第一个 row
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionMiddle
                                  animated:YES];
    [self.tableView reloadData];
    self.stepL.text = [NSString stringWithFormat:@"%lu/%lu", (unsigned long)(self.currentIndex + 1),(unsigned long)self.dataArr.count];
    self.progressView.progress = (float)self.currentIndex/(self.dataArr.count - 1);
    if (self.currentIndex >= self.dataArr.count - 1) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.currentIndex ++;

}
- (void)changeModel {
    self.scoreView.hidden = YES;
    [[PlayManager sharPlayManager] pause];
    [self.recordHelper stopRecord];
    [self.detection stop];
    [self.pcmPlay stop];
}
- (void)next {
    [self changeModel];
    if(self.currentIndex == self.dataArr.count-1){
        DebugLog(@"============最后一个");
        SubmitWorkViewController *vc = [[SubmitWorkViewController alloc] init];
        vc.dataArr = self.dataArr;
        vc.type = @"课文";
        vc.unitWordModel = self.unitWordModel;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    self.currentIndex = self.currentIndex+1;

    TextBookUnitTextModel *model = self.dataArr[self.currentIndex];
    model.isRead = !model.isRead;
    [self lesson];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0]; // 滚动到第一个 section 的第一个 row
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionMiddle
                                  animated:YES];
    [self.tableView reloadData];
    self.stepL.text = [NSString stringWithFormat:@"%lu/%lu", (unsigned long)(self.currentIndex + 1),(unsigned long)self.dataArr.count];
    self.progressView.progress = (float)self.currentIndex/(self.dataArr.count - 1);
}
- (void)pre {
    [self changeModel];
    if(self.currentIndex == 0){
        DebugLog(@"============第一个");
        return;
    }
    [[PlayManager sharPlayManager] pause];
    self.currentIndex = self.currentIndex-1;
    [self.tableView reloadData];
}

- (void)play {
    [[PlayManager sharPlayManager] pause];
}
- (void)lesson {
    [self changeModel];
    TextBookUnitTextModel *currentModel = self.dataArr[self.currentIndex];
    NSString *imurl = [NSString stringWithFormat:@"%@%@",self.baseUrl,currentModel.audioUrl];
    [[PlayManager sharPlayManager] playerWithURL:imurl];

}
- (void)recordTextWithText:(NSString *)text {
    [self changeModel];
    //开始录音
    void(^StartSpeakingVoice)(void) = ^() {
        TextBookUnitTextModel *currentModel = self.dataArr[self.currentIndex];
        [self.detection startEvalutingWord:[NSString stringWithFormat:@"%@",currentModel.name]];

        [self.recordHelper startRecord:currentModel.recordPath];
    };
    
    //检测是否授权麦克风
    void(^CheckOutAuthorization)(void) = ^() {
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            //第一次询问用户是否进行授权
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                if (granted) {
                    StartSpeakingVoice();
                }
            }];
        }
        else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
            NSString *message = @"\n麦克风权限未开启，请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能";
            [self alertViewTitle:@"麦克风权限未开启" message:message left:@"确定" leftBlock:^{
                
            } right:@"前往" rightBlock:^{
                //跳入当前App设置界面
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
        }
        else{// 已授权
            StartSpeakingVoice();
        }
    };
    
    CheckOutAuthorization();

}

#pragma mark - PlayManagerDelegate
- (void)musicFinsh {
    DebugLog(@"===========");
}
- (void)playStateChange:(AVPlayerItemStatus)state {
    [self removeLoadingView];
}

#pragma mark - IFlyDetectionDelegate
- (void)evaluting:(IFlyDetection *)ifyldetection result:(NSString *)result {
    
    //评测分数
    CGFloat totalScore = 0;
    NSArray<NSString*> *words = [result componentsSeparatedByString:@"\n"];
    for (NSString *obj in words) {
        NSString *searchWord = @"Total Score：";
        if ([obj containsString:searchWord]) {
            totalScore = [[obj substringFromIndex:searchWord.length] floatValue];
        }
    }
    DebugLog(@"评测结果: %@ == %f",result,totalScore);

    self.scoreView.hidden = NO;
    self.scoreView.scoreLB.text = [NSString stringWithFormat:@"%.1f 分",totalScore];
    self.scoreView.wanchengLB.text = [NSString stringWithFormat:@"完整度  %.1f",totalScore];
    self.scoreView.liuliLB.text = [NSString stringWithFormat:@"流利度  %.1f",totalScore];
    self.scoreView.zhunqueLB.text = [NSString stringWithFormat:@"准确度  %.1f",totalScore];
    TextBookUnitTextModel *currentModel = self.dataArr[self.currentIndex];
    currentModel.isRead = YES;
    currentModel.totalScore = totalScore;
    currentModel.completionDegree = totalScore;
    currentModel.accurateDegree = totalScore;
    currentModel.fluentDegree = totalScore;
    [self.tableView reloadData];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:currentModel.recordPath]) {
        [HomeRequest upLoadAudioWithPath:currentModel.recordPath result:^(NSDictionary *url) {
            if (!IsStrEmpty(url[@"fullurl"])) {
                TextBookUnitWordModel *model = self.dataArr[self.currentIndex];
                model.recordUrl = url[@"fullurl"];
            }
        }];
    }
    if(self.isAutomatic){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self next];
        });
    }
}


- (IFlyDetection *)detection {
    if (!_detection) {
        _detection = [[IFlyDetection alloc] init];
        _detection.delegate = self;
    }
    return _detection;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.detection cancle];
    [[PlayManager sharPlayManager] pause];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

@end
